#!/usr/bin/env python
# -*- conding: utf-8 -*-

"""
@Time     : 2024/10/28 6:53
@Author   : liujingmao
@File     : 1.预构建ReACT智能体.py
"""

import dotenv
from langchain_community.tools import GoogleSerperRun
from langchain_community.tools.openai_dalle_image_generation import OpenAIDALLEImageGenerationTool
from langchain_community.utilities import GoogleSerperAPIWrapper
from langchain_community.utilities.dalle_image_generator import DallEAPIWrapper
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent

dotenv.load_dotenv()


class GoogleSerperArgsSchema(BaseModel):
    query: str = Field(description="执行谷歌搜索的查询语句")


class DallEArgsSchema(BaseModel):
    query: str = Field(description="输入应该是生成图像的文本提示(prompt)")


# 1.定义工具与工具列表
google_serper = GoogleSerperRun(
    name="google_serper",
    description=(
        "一个低成本的谷歌搜索API。"
        "当你需要回答有关时事的问题时，可以调用该工具。"
        "该工具的输入是搜索查询语句。"
    ),
    args_schema=GoogleSerperArgsSchema,
    api_wrapper=GoogleSerperAPIWrapper(),
)
dalle = OpenAIDALLEImageGenerationTool(
    name="openai_dalle",
    api_wrapper=DallEAPIWrapper(model="dall-e-3"),
    args_schema=DallEArgsSchema,
)
tools = [google_serper, dalle]

# 2.创建大语言模型
model = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# 3.使用预构建的函数创建ReACT智能体
agent = create_react_agent(model=model, tools=tools)

# 4.调用智能体并输出内容
print(agent.invoke({"messages": [("human", "请帮我绘制一幅鲨鱼在天上飞的图片")]}))

"""
输出结果：
E:\code\llmops\llmops-api\venv\Scripts\python.exe E:\code\llmops\llmops-api\study\67-LangGraph实现ReACT架构Agent\1.预构建ReACT智能体.py 
sys:1: LangChainDeprecationWarning: 
As of langchain-core 0.3.0, LangChain uses pydantic v2 internally. The langchain_core.pydantic_v1 module was a compatibility shim for pydantic v1, and should no longer be used. Please update the code to import from Pydantic directly.

For example, replace imports like: `from langchain_core.pydantic_v1 import BaseModel`
with: `from pydantic import BaseModel`
or the v1 compatibility namespace if
 you are working in a code base that has not been 
 fully upgraded to pydantic 2 yet. 	from pydantic.v1 
 import BaseModel

{'messages': [HumanMessage(content='请帮我绘制一幅鲨鱼在天上飞的图片', 
additional_kwargs={}, response_metadata={}, 
id='44c21d46-da7e-457f-ab67-050f9b07143e'), 
AIMessage(content='', 
additional_kwargs={'tool_calls': [{'id': 'call_e4uixJVydKyJZSP1yEjPtSEY', 'function': {'arguments': '{"query":"A surreal image of a shark flying in the sky, surrounded by fluffy clouds and a bright blue sky. 
The shark is depicted in a dynamic pose, with its fins spread out as if
 gliding through the air. The scene is whimsical and imaginative, 
 capturing the essence of fantasy."}', 'name': 'openai_dalle'}, 
 'type': 'function'}], 'refusal': None}, 
 response_metadata={'token_usage': {'completion_tokens': 71, 'prompt_tokens': 169, 'total_tokens': 240, 
 'completion_tokens_details': {'reasoning_tokens': 0}, 
 'prompt_tokens_details': {'cached_tokens': 0}}, 
 'model_name': 'gpt-4o-mini-2024-07-18', 
 'system_fingerprint': 'fp_f59a81427f', 
 'finish_reason': 'tool_calls', 
 'logprobs': None}, id='run-b0d6c23f-c5f6-4ee1-a679-5dcd05f30dae-0', 
 tool_calls=[{'name': 'openai_dalle', 
 'args': {'query': 'A surreal image of a shark flying in the sky, 
 surrounded by fluffy clouds and a bright blue sky. 
 The shark is depicted in a dynamic pose, with its 
 fins spread out as if gliding through the air. 
 The scene is whimsical and imaginative, 
 capturing the essence of fantasy.'}, 
 'id': 'call_e4uixJVydKyJZSP1yEjPtSEY', 
 'type': 'tool_call'}], usage_metadata={'input_tokens': 169, 'output_tokens': 71, 'total_tokens': 240, 'input_token_details': {'cache_read': 0}, 'output_token_details': {'reasoning': 0}}), ToolMessage(content='Error: AuthenticationError("Error code: 401 - {\'error\': {\'code\': \'invalid_api_key\', \'message\': \'Incorrect API key provided: **********. You can find your API key at https://platform.openai.com/account/api-keys.\', \'param\': None, \'type\': \'invalid_request_error\'}}")\n Please fix your mistakes.', name='openai_dalle', id='ac66e734-d45f-49f0-b1ce-8a98037a64ec', tool_call_id='call_e4uixJVydKyJZSP1yEjPtSEY'), AIMessage(content='目前我无法生成图像，但我可以帮助你描述这幅画，或者你可以使用其他图像生成工具来实现这个想法。如果你需要，我可以提供一些建议或灵感！', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 43, 'prompt_tokens': 321, 'total_tokens': 364, 'completion_tokens_details': {'reasoning_tokens': 0}, 'prompt_tokens_details': {'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_f59a81427f', 'finish_reason': 'stop', 'logprobs': None}, id='run-84a72e38-81c0-467a-adcd-0e4da521a0fa-0', usage_metadata={'input_tokens': 321, 'output_tokens': 43, 'total_tokens': 364, 'input_token_details': {'cache_read': 0}, 'output_token_details': {'reasoning': 0}})]}

Process finished with exit code 0


"""
